package com.aiti.lulian.service.newCard;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.CardEnterpriseTemplateDto;
import com.aiti.lulian.dto.ShowRecordAuditDto;
import com.aiti.lulian.dto.TemplateListDto;
import com.aiti.lulian.dto.newCard.*;
import com.aiti.lulian.entity.CardEnterpriseTemplate;
import com.aiti.lulian.entity.CardTemplateStyleField;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.newCard.*;
import com.aiti.lulian.mapper.CardEnterpriseTemplateMapper;
import com.aiti.lulian.mapper.CardTemplateStyleFieldMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseMapper;
import com.aiti.lulian.mapper.newCard.*;
import com.aiti.lulian.service.CardEnterpriseMaterialService;
import com.aiti.lulian.service.CardEnterpriseTemplateService;
import com.aiti.lulian.service.CardTemplateStyleFieldService;
import com.aiti.lulian.service.ShowRecordAuditService;
import com.aiti.lulian.utils.MyStrUtil;
import com.aiti.lulian.vo.CardEnterpriseTemplateDetailInfoVo;
import com.aiti.lulian.vo.PreSetTemplateListVo;
import com.aiti.lulian.vo.ShowRecordAuditVo;
import com.aiti.lulian.vo.TemplateListVo;
import com.aiti.lulian.vo.newCard.*;
import com.aiti.lulian.workflow.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-08-25 15:02
 **/
@Service
@Slf4j
public class CardEnterpriseTemplateNewService extends BaseSerivceImpl<CardEnterpriseTemplateNewMapper, CardEnterpriseTemplateNew> {

    @Autowired
    private CardEnterpriseComponentService cardEnterpriseComponentService;
    @Autowired
    private CardEnterpriseComponentMapper cardEnterpriseComponentMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private CardEnterpriseTemplateService cardEnterpriseTemplateService;
    @Autowired
    private CardEnterpriseTemplateMapper cardEnterpriseTemplateMapper;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private ShowEnterpriseTrialMapper showEnterpriseTrialMapper;
    @Autowired
    private CardComponentDataMapper cardComponentDataMapper;
    @Autowired
    private CardComponentDataService cardComponentDataService;
    @Autowired
    private CardPersonalFileInfoMapper cardPersonalFileInfoMapper;
    @Autowired
    private CardPersonalFileInfoService cardPersonalFileInfoService;
    @Autowired
    private CardVideoInfoService cardVideoInfoService;
    @Autowired
    private CardVideoInfoMapper cardVideoInfoMapper;
    @Autowired
    private WorkflowEngine workflowEngine;
    @Autowired
    private TaskManager taskManager;
    @Autowired
    private ShowRecordAuditService showRecordAuditService;
    @Autowired
    private CardEnterpriseMaterialService cardEnterpriseMaterialService;
    @Autowired
    private CardTemplateStyleFieldService styleFieldService;
    @Autowired
    private CardLinkInfoService cardLinkInfoService;
    @Autowired
    private CardShareConfigService cardShareConfigService;
    @Autowired
    private CardTemplateStyleFieldService cardTemplateStyleFieldService;
    @Autowired
    private CardStyleFieldDataService cardStyleFieldDataService;
    @Autowired
    private CardAuditMapper cardAuditMapper;
    @Autowired
    private EnterpriseNewCardService enterpriseNewCardService;
    @Autowired
    private CardTemplateStyleFieldMapper cardTemplateStyleFieldMapper;


    /**
     * 查询模板信息
     * @param templateId
     * @return
     */
    public TemplateComponentVo  queryTemplateInfo(String templateId) {
        List<CardEnterpriseComponent> componentList = cardEnterpriseComponentMapper.queryCardEnterpriseComponentList(templateId);
        if(CollectionUtil.isEmpty(componentList)) {
            return null;
        }
        TemplateComponentVo templateComponentVo = new TemplateComponentVo();
        templateComponentVo.setTemplateId(templateId);
        List<TemplateComponentDto> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent component : componentList) {
            TemplateComponentDto componentDto = new TemplateComponentDto();
            componentDto.setComponentId(component.getBaseId());
            componentDto.setComponentType(component.getComponentType());
            componentDto.setComponentBusinessData(component.getComponentBusinessData());
            componentDto.setSort(component.getSort());
            componentDto.setComponentPermission(component.getComponentPermission());
            componentDto.setComponentPageId(component.getComponentPageId());
            if(NewCardBusinessConstant.ENTERPRISE_PRODUCT.equals(component.getComponentType())) {
                // 产品组件的数据，将保存的产品id转换为具体的产品数据
                JSONObject productMetaData = this.setProductInfo(component);
                componentDto.setComponentMetaData(productMetaData);
            }else if(NewCardBusinessConstant.ENTERPRISE_SERVICE.equals(component.getComponentType())) {
                // 服务组件的数据，将保存的服务id转换为具体服务数据
                JSONObject serviceMetaData = this.setEnterpriseServiceInfo(component);
                componentDto.setComponentMetaData(serviceMetaData);
            } else if(NewCardBusinessConstant.FILE.equals(component.getComponentType())) {
                // 文件组件，从文件的审核结果表中查询数据
                componentDto.setComponentMetaData(this.setFileInfo(component));
            } else if(NewCardBusinessConstant.ENTERPRISE_MATERIAL.equals(component.getComponentType())) {
                // 物料组件，从物料表中查询数据，将物料id转换为物料的详情数据
                componentDto.setComponentMetaData(this.setEnterpriseMaterialInfo(component));
            } else if(NewCardBusinessConstant.COMPANY.equals(component.getComponentType()) || NewCardBusinessConstant.BUSINESS.equals(component.getComponentType())) {
                // 企业介绍和业务介绍属于图文组件，该组件中可能包含视频。查询视频的审核结果
                componentDto.setComponentMetaData(this.setImageTextInfo(component));
            }
            else {
                componentDto.setComponentMetaData(JSONObject.parseObject(component.getComponentMetaData()));
            }
            componentDataList.add(componentDto);
        }
        templateComponentVo.setComponentDataList(componentDataList);
        return templateComponentVo;
    }

    /**
     * 保存或更新模板信息。
     * 模板应该是跟随着模板内的数据一块创建的，如果选择了预制模板但是不保存，不会创建模板
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateTemplateInfo(EnterpriseCardTemplateComponentDto dto) {
        this.checkParam(dto);
        String userCardId = dto.getCardId();
        if(StrUtil.isEmpty(userCardId)){
            throw new BusinessException("名片id不能为空");
        }
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(userCardId);
        if(cardBaseInfo == null){
            throw new BusinessException("名片不存在");
        }
        Date expireTime = cardBaseInfo.getExpireTime();
        if(expireTime != null && expireTime.getTime() < System.currentTimeMillis()){
            throw new BusinessException("当前名片已过期，请续费");
        }

        String templateId = "";
        // 1. 如果没有模板，则先创建模板
        if(StrUtil.isBlank(dto.getTemplateId())) {
            templateId = this.createTemplate(dto);
            //创建模板的分享配置
            CardShareConfig cardShareConfig = cardShareConfigService.buildCardShareConfig(dto.getEnterpriseId(), templateId);
            cardShareConfigService.save(cardShareConfig);
        }else {
            templateId = dto.getTemplateId();
            this.updateTemplate(dto);
        }
        // 2. 删除模板组件数据
        if(CollectionUtil.isNotEmpty(dto.getDeleteComponentIdList())) {
            cardEnterpriseComponentService.removeByIds(dto.getDeleteComponentIdList());
            // 删除使用这些组件的名片上的数据
            cardComponentDataMapper.deleteByTemplateComponentIdList(dto.getDeleteComponentIdList());
        }
        // 3. 保存模板组件数据
        if(CollectionUtil.isEmpty(dto.getComponentDataList())) {
            return;
        }
        // 查出所有使用该模板的名片
        List<String> useCurTemplateCardIdList = cardAuditMapper.queryCardIdList(templateId, null);
        List<CardEnterpriseComponent> updateComponentList = new ArrayList<>();
        List<CardEnterpriseComponent> addComponentList = new ArrayList<>();
        int sort = 1;
        for(TemplateComponentDto componentDto : dto.getComponentDataList()) {
            // 如果组件是文件类型，则解析文件id，并保存文件id。同时将文件提交审核
            if(NewCardBusinessConstant.FILE.equals(componentDto.getComponentType())) {
                this.setFileComponentData(templateId, componentDto);
            }
            // 企业介绍和业务介绍组件都属于图片文本类型，里面可能包含视频。将提交的视频相关的数据进行处理并提交审核
            if(NewCardBusinessConstant.COMPANY.equals(componentDto.getComponentType()) || NewCardBusinessConstant.BUSINESS.equals(componentDto.getComponentType())) {
                this.setImageTextComponentData(templateId, componentDto);
            }
            // 企业实景组件中的主营产品更新到企业表或试用企业表
            if(NewCardBusinessConstant.ENTERPRISE_REALITY.equals(componentDto.getComponentType())) {
                this.updateEnterpriseMainProducts(dto.getEnterpriseId(), componentDto);
            }
            // 如果组件id存在，则更新组件数据，否则新建数据
            if(StrUtil.isNotBlank(componentDto.getComponentId())) {
                CardEnterpriseComponent updateComponent = new CardEnterpriseComponent();
                updateComponent.setBaseId(componentDto.getComponentId());
                updateComponent.setComponentPageId(componentDto.getComponentPageId());
                updateComponent.setComponentPermission(componentDto.getComponentPermission());
                this.setComponentData(componentDto, updateComponent, sort);
                updateComponentList.add(updateComponent);
            }else {
                CardEnterpriseComponent addComponent = new CardEnterpriseComponent();
                addComponent.setBaseId(IdUtil.simpleUUID());
                addComponent.setTemplateId(templateId);
                addComponent.setComponentPermission(componentDto.getComponentPermission());
                addComponent.setComponentPageId(componentDto.getComponentPageId());
                this.setComponentData(componentDto, addComponent, sort);
                addComponentList.add(addComponent);
            }
            sort++;
        }
        if(CollectionUtil.isNotEmpty(updateComponentList)) {
            cardEnterpriseComponentService.updateBatchById(updateComponentList);
            // 根据组件权限更新使用该模板的名片的对应组件的数据。
            // 保存名片组件数据的表中template_component_id字段是模板组件表组件的主键，所以更新的数据是：template_component_id = 模板组件id，meta_data = 模板组件数据
            for(CardEnterpriseComponent component : updateComponentList) {
                if(component.getComponentPermission() == null || component.getComponentPermission().equals(NewCardBusinessConstant.TEMPLATE_COMPONENT_PERMISSION_1)) {
                    cardComponentDataMapper.updateCardComponentData(component.getBaseId(), component.getComponentMetaData(), component.getSort());
                }else {
                    cardComponentDataMapper.updateCardComponentDataSort(component.getBaseId(), component.getSort());
                }
            }
        }
        if(CollectionUtil.isNotEmpty(addComponentList)) {
            cardEnterpriseComponentService.saveBatch(addComponentList);

            if(CollectionUtil.isNotEmpty(useCurTemplateCardIdList)) {
                for(String cardId : useCurTemplateCardIdList) {
                    List<CardComponentData> newCardComponentDataList = new ArrayList<>();
                    for(CardEnterpriseComponent component : addComponentList) {
                        CardComponentData cardComponentData = this.buildCardComponentData(cardId, component);
                        newCardComponentDataList.add(cardComponentData);
                    }
                    cardComponentDataService.saveBatch(newCardComponentDataList);
                }
            }
        }
        CardEnterpriseTemplateDto subTemplate = dto.getSubTemplate();
        if(subTemplate != null){
            subTemplate.setNewTemplateId(templateId);
            String baseId = subTemplate.getBaseId();
            if(StringUtils.isEmpty(baseId)){
                cardEnterpriseTemplateService.saveTemplate(subTemplate);
            }else{
                cardEnterpriseTemplateService.updateTemplate(subTemplate);
            }


        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteEnterpriseTemplate(String templateId, String userId) {
        Integer templateCardCount = cardAuditMapper.queryCardAuditCountByTemplateId(templateId);
        if(templateCardCount > 0) {
            throw new BusinessException("该模板下已存在名片数据，不可删除");
        }
//        CardEnterpriseTemplateNew newTemplate = new CardEnterpriseTemplateNew();
//        newTemplate.setBaseId(templateId);
//        newTemplate.setBaseUpdateBy(userId);
//        newTemplate.setBaseUpdateTime(new Date());
//        newTemplate.setIsDelete(1);
//        this.baseMapper.updateById(newTemplate);
//        CardEnterpriseTemplate cardEnterpriseTemplate = cardEnterpriseTemplateMapper.queryEnterpriseTemplateInfo(templateId);
//        if(cardEnterpriseTemplate != null) {
//            CardEnterpriseTemplate updateTemplate = new CardEnterpriseTemplate();
//            updateTemplate.setBaseId(cardEnterpriseTemplate.getBaseId());
//            updateTemplate.setIsDelete("1");
//            updateTemplate.setUpdateBy(userId);
//            updateTemplate.setBaseUpdateTime(new Date());
//            cardEnterpriseTemplateMapper.updateById(updateTemplate);
//        }
        // 物理删除部分相关表，审核文件和视频的数据暂时没删
        // 旧模板表数据、背景、字段
        cardEnterpriseTemplateService.deleteByNewTemplateId(templateId);
        // 删除模板组件数据
        cardEnterpriseComponentMapper.deleteByTemplateId(templateId);
        // 新模板表
        this.baseMapper.deleteById(templateId);
    }

    private void setFileComponentData(String templateId, TemplateComponentDto componentDto) {
        JSONObject fileMetaData = componentDto.getComponentMetaData();
        List<String> fileIdList = new ArrayList<>();
        fileMetaData.put("fileIdList", fileIdList);
        JSONArray fileList = fileMetaData.getJSONArray("fileList");
        if(CollectionUtil.isNotEmpty(fileList)) {
            List<CardPersonalFileInfo> fileInfoList = new ArrayList<>();
            for(int i = 0; i < fileList.size(); i++) {
                JSONObject jsonObject = fileList.getJSONObject(i);
                String fileId = MyStrUtil.getFileIdByUrl(jsonObject.getString("filePath"));
                if(StrUtil.isNotEmpty(fileId)) {
                    fileIdList.add(fileId);
                    fileInfoList.add(this.buildPersonalFileInfo(templateId, fileId, jsonObject));
                }
            }
            // todo 提交文件审核
            cardPersonalFileInfoService.saveBatch(fileInfoList);
        }
    }

    private void setImageTextComponentData(String templateId, TemplateComponentDto componentDto) {
        JSONObject imageTextMetaData = componentDto.getComponentMetaData();
        JSONArray imageTextList = imageTextMetaData.getJSONArray("textList");
        if(CollectionUtil.isNotEmpty(imageTextList)) {
            List<CardVideoInfo> videoInfoList = new ArrayList<>();
            for(int i = 0; i < imageTextList.size(); i++) {
                JSONObject imageTextItem = imageTextList.getJSONObject(i);
                String type = imageTextItem.getString("type");
                if("video".equals(type)) {
                    CardVideoInfo cardVideoInfo = this.buildCardVideoInfo(templateId, imageTextItem);
                    // 这里添加一个属性videoId，用于在回显时找到该视频的审核结果
                    imageTextItem.put("videoId", cardVideoInfo.getBaseId());
                    videoInfoList.add(cardVideoInfo);
                }
            }
            // todo 提交视频审核
            cardVideoInfoService.saveBatch(videoInfoList);
        }
    }

    private void updateEnterpriseMainProducts(String enterpriseId, TemplateComponentDto componentDto) {
        JSONObject metaData = componentDto.getComponentMetaData();
        String mainProducts = metaData.getString("mainProducts");
        luLianEnterpriseMapper.updateEnterpriseMainProducts(enterpriseId, mainProducts);
        showEnterpriseTrialMapper.updateEnterpriseMainProducts(enterpriseId, mainProducts);
    }

    private CardPersonalFileInfo buildPersonalFileInfo(String templateId, String fileId, JSONObject jsonObject) {
        CardPersonalFileInfo fileInfo = new CardPersonalFileInfo();
        fileInfo.setBaseId(IdUtil.simpleUUID());
        fileInfo.setBaseInfoId(templateId);
        fileInfo.setFileId(fileId);
        String fileName = jsonObject.getString("fileName");
        fileInfo.setFileName(fileName);
        fileInfo.setFileExt(FileUtil.extName(fileName));
        fileInfo.setFileSize(jsonObject.getInteger("size"));
        fileInfo.setFileUrl(jsonObject.getString("filePath"));
        fileInfo.setStatus(NewCardBusinessConstant.AUDIT_STATUS_2);
        return fileInfo;
    }

    private CardVideoInfo buildCardVideoInfo(String templateId, JSONObject imageTextItem) {
        CardVideoInfo videoInfo = new CardVideoInfo();
        String videoUrl = imageTextItem.getString("content");
        if(StrUtil.isBlank(videoUrl)) {
            videoUrl = imageTextItem.getString("url");
            if(StrUtil.isBlank(videoUrl)) {
                throw new BusinessException("提取视频访问路径失败");
            }
        }
        String videoId = MyStrUtil.getVideoIdByUrl(videoUrl);
        videoInfo.setBaseId(IdUtil.simpleUUID());
        videoInfo.setBaseInfoId(templateId);
        String videoName = imageTextItem.getString("name");
        videoInfo.setVideoName(videoName);
        videoInfo.setVideoUrl(videoUrl);
        videoInfo.setVideoFullPath(NewCardBusinessConstant.VIDEO_FILE_PATH + MyStrUtil.getFileIdByUrl(videoUrl));
        videoInfo.setStatus(NewCardBusinessConstant.AUDIT_STATUS_2);
        videoInfo.setBaseCreateTime(new Date());
        return videoInfo;
    }

    private CardComponentData buildCardComponentData(String cardId, CardEnterpriseComponent component) {
        CardComponentData cardComponentData = new CardComponentData();
        cardComponentData.setBaseId(IdUtil.simpleUUID());
        cardComponentData.setCardId(cardId);
        cardComponentData.setTemplateComponentId(component.getBaseId());
        cardComponentData.setComponentMetaData(component.getComponentMetaData());
        cardComponentData.setSort(component.getSort());
        return cardComponentData;
    }

    /**
     * 获取企业媒体信息
     * @param enterpriseId
     * @return
     */
    public EnterpriseMediaInfoVo getEnterpriseMediaInfo(String enterpriseId) {
        EnterpriseMediaInfoVo enterpriseMediaInfoVo = new EnterpriseMediaInfoVo();
        LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(enterpriseId);
        if(luLianEnterprise == null) {
            // show_enterprise表中不存在，应该是试用的企业
            ShowEnterpriseTrial showEnterpriseTrial = showEnterpriseTrialMapper.selectById(enterpriseId);
            if(showEnterpriseTrial == null) {
                throw new BusinessException("当前企业不存在");
            }
            luLianEnterprise = new LuLianEnterprise();
            BeanUtils.copyProperties(showEnterpriseTrial, luLianEnterprise);
        }
        EnterpriseMediaDto enterpriseMediaDto = this.baseMapper.queryEnterpriseMediaInfo(enterpriseId);
        enterpriseMediaInfoVo.setVrGif(luLianEnterprise.getVrGif());
        enterpriseMediaInfoVo.setVrUrl(luLianEnterprise.getVrUrl());
        if(enterpriseMediaDto != null) {
            enterpriseMediaInfoVo.setMediaPath(enterpriseMediaDto.getMediaPath());
            enterpriseMediaInfoVo.setMediaBaseId(enterpriseMediaDto.getBaseId());
        }
        enterpriseMediaInfoVo.setHyMainPic(luLianEnterprise.getHyMainPic());
        enterpriseMediaInfoVo.setLogo(luLianEnterprise.getLogo());
        enterpriseMediaInfoVo.setEnterpriseName(luLianEnterprise.getBaseName());
        enterpriseMediaInfoVo.setMainProducts(luLianEnterprise.getMainProducts());
        enterpriseMediaInfoVo.setSdzzYszt(luLianEnterprise.getSdzzYszt());
        enterpriseMediaInfoVo.setSdzzPprd(luLianEnterprise.getSdzzPprd());
        List<String> tagList = this.buildEnterpriseTagList(luLianEnterprise);
        enterpriseMediaInfoVo.setEnterpriseTagList(tagList);
        return enterpriseMediaInfoVo;
    }

    /**
     * 获取企业产品列表，给产品组件选择
     * @param enterpriseId
     * @return
     */
    public List<EnterpriseProductVo> getEnterpriseProductList(String enterpriseId) {
        List<EnterpriseProductVo> enterpriseProductList = cardEnterpriseComponentMapper.queryEnterpriseProductList(enterpriseId);
        return enterpriseProductList;
    }

    /**
     * 获取企业服务列表，给服务组件选择
     * @param enterpriseId
     * @return
     */
    public List<EnterpriseServiceVo> getEnterpriseServiceList(String enterpriseId) {
        List<EnterpriseServiceVo> enterpriseServiceList = cardEnterpriseComponentMapper.queryEnterpriseServiceList(enterpriseId);
        return enterpriseServiceList;
    }

    /**
     * 查询企业物料列表，给物料组件选择
     * @param enterpriseId
     * @return
     */
    public List<EnterpriseMaterialVo> getEnterpriseMaterialList(String enterpriseId) {
        List<EnterpriseMaterialVo> enterpriseMaterialList = cardEnterpriseComponentMapper.queryEnterpriseMaterialList(enterpriseId);
        return enterpriseMaterialList;
    }

    // 设置商品数据，返回前端
    private JSONObject setProductInfo(CardEnterpriseComponent component) {
        JSONObject productMetaData = JSONObject.parseObject(component.getComponentMetaData());
        JSONArray productIdList = productMetaData.getJSONArray("productList");
        if(productIdList != null && !productIdList.isEmpty()) {
            List<String> idList = new ArrayList<>();
            for(int i = 0; i < productIdList.size(); i++) {
                idList.add(productIdList.getString(i));
            }
            List<EnterpriseProductVo> enterpriseProductList = cardEnterpriseComponentMapper.queryProductList(idList);
            List<EnterpriseProductVo> sortedProductList = new ArrayList<>();
            for(String id : idList) {
                for(EnterpriseProductVo product : enterpriseProductList) {
                    if(id.equals(product.getProductId())) {
                        sortedProductList.add(product);
                        break;
                    }
                }
            }
            productMetaData.put("productInfoList", sortedProductList);
        }else {
            productMetaData.put("productInfoList", new ArrayList<>());
        }
        return productMetaData;
    }

    // 设置企业服务数据，返回前端
    private JSONObject setEnterpriseServiceInfo(CardEnterpriseComponent component) {
        JSONObject serviceMetaData = JSONObject.parseObject(component.getComponentMetaData());
        JSONArray serviceIdList = serviceMetaData.getJSONArray("introduceList");
        if(serviceIdList != null && !serviceIdList.isEmpty()) {
            List<String> idList = new ArrayList<>();
            for(int i = 0; i < serviceIdList.size(); i++) {
                idList.add(serviceIdList.getString(i));
            }
            List<EnterpriseServiceVo> enterpriseServiceList = cardEnterpriseComponentMapper.queryServiceList(idList);
            List<EnterpriseServiceVo> sortedServiceList = new ArrayList<>();
            for(String id : idList) {
                for(EnterpriseServiceVo service : enterpriseServiceList) {
                    if(id.equals(service.getEnterpriseServiceId())) {
                        sortedServiceList.add(service);
                        break;
                    }
                }
            }
            serviceMetaData.put("introduceInfoList", sortedServiceList);
        }else {
            serviceMetaData.put("introduceInfoList", new ArrayList<>());
        }
        return serviceMetaData;
    }

    // 获取文件数据，返回前端
    private JSONObject setFileInfo(CardEnterpriseComponent component) {
        JSONObject fileMetaData = JSONObject.parseObject(component.getComponentMetaData());
        JSONArray fileIdList = fileMetaData.getJSONArray("fileIdList");
        if(fileIdList != null && !fileIdList.isEmpty()) {
            List<String> idList = new ArrayList<>();
            for(int i = 0; i < fileIdList.size(); i++) {
                idList.add(fileIdList.getString(i));
            }
            List<ComponentFileVo> componentFileList = cardEnterpriseComponentMapper.queryComponentFileList(idList);
            List<ComponentFileVo> sortedFileList = new ArrayList<>();
            for(String id : idList) {
                for(ComponentFileVo file : componentFileList) {
                    if(id.equals(file.getFileId())) {
                        sortedFileList.add(file);
                        break;
                    }
                }
            }
            fileMetaData.put("fileInfoList", sortedFileList);
        }else {
            fileMetaData.put("fileInfoList", new ArrayList<>());
        }
        return fileMetaData;
    }

    // 获取物料数据，返回前端
    private JSONObject setEnterpriseMaterialInfo(CardEnterpriseComponent component) {
        JSONObject materialMetaData = JSONObject.parseObject(component.getComponentMetaData());
        JSONArray materialIdList = materialMetaData.getJSONArray("materialList");
        if(materialIdList != null && !materialIdList.isEmpty()) {
            List<String> idList = new ArrayList<>();
            for(int i = 0; i < materialIdList.size(); i++) {
                idList.add(materialIdList.getString(i));
            }
            List<EnterpriseMaterialVo> enterpriseMaterialList = cardEnterpriseComponentMapper.queryEnterpriseMaterialInfoList(idList);
            List<EnterpriseMaterialVo> sortedMaterialList = new ArrayList<>();
            for(String id : idList) {
                for(EnterpriseMaterialVo material : enterpriseMaterialList) {
                    if(id.equals(material.getMaterialId())) {
                        sortedMaterialList.add(material);
                        break;
                    }
                }
            }
            materialMetaData.put("materialInfoList", sortedMaterialList);
        }else {
            materialMetaData.put("materialInfoList", new ArrayList<>());
        }
        return materialMetaData;
    }

    // 如果图文组件中包含视频，查询视频的审核结果，返回前端
    public JSONObject setImageTextInfo(CardEnterpriseComponent component) {
        JSONObject imageTextMetaData = JSONObject.parseObject(component.getComponentMetaData());
        JSONArray textList = imageTextMetaData.getJSONArray("textList");
        if(textList != null && !textList.isEmpty()) {
            List<String> idList = new ArrayList<>();
            for(int i = 0; i < textList.size(); i++) {
                JSONObject imageTextItem = textList.getJSONObject(i);
                String type = imageTextItem.getString("type");
                if(StrUtil.isNotEmpty( type) && "video".equals(type)) {
                    idList.add(imageTextItem.getString("videoId"));
                    // 防止某些情况下不反回给前端这个字段，所以先设置审核状态为待审核，下面会修改该字段
                    imageTextItem.put("auditStatus", NewCardBusinessConstant.AUDIT_STATUS_2);
                }
            }
            if(!idList.isEmpty()) {
                // 查询视频的审核结果
                List<CardVideoInfo> cardVideoInfoList = cardEnterpriseComponentMapper.queryVideoInfoList(idList);
                // 设置对应视频的审核结果
                for(int i = 0; i < textList.size(); i++) {
                    JSONObject imageTextItem = textList.getJSONObject(i);
                    String type = imageTextItem.getString("type");
                    if(StrUtil.isNotEmpty( type) && "video".equals(type)) {
                        for(CardVideoInfo videoInfo : cardVideoInfoList) {
                            if(imageTextItem.getString("videoId").equals(videoInfo.getBaseId())) {
                                imageTextItem.put("auditStatus", videoInfo.getStatus());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return imageTextMetaData;
    }

    private List<String> buildEnterpriseTagList(LuLianEnterprise luLianEnterprise) {
        List<String> tagList = new ArrayList<>();
        if(luLianEnterprise.getIsLead()) {
            tagList.add("龙头企业");
        }
        if(luLianEnterprise.getIsGazelle()) {
            tagList.add("瞪羚企业");
        }
        if(luLianEnterprise.getIsChampion()) {
            tagList.add("单项冠军");
        }
        if(luLianEnterprise.getIsSpecial()) {
            tagList.add("专精特新");
        }
        if(luLianEnterprise.getIsGiant()) {
            tagList.add("小巨人");
        }
        if(luLianEnterprise.getIsUnicorn()) {
            tagList.add("独角兽");
        }
        if(luLianEnterprise.getIsHightech()) {
            tagList.add("高新技术企业");
        }
        return tagList;
    }

    private void setComponentData(TemplateComponentDto componentDto, CardEnterpriseComponent addComponent, int sort) {
        addComponent.setComponentType(componentDto.getComponentType());
        if(componentDto.getComponentMetaData() != null) {
            // 保存的是否不需要这些详情数据，只需要存储对应的id，所以这里删除这些属性
            JSONObject componentMetaData = componentDto.getComponentMetaData();
            if(componentMetaData.get("fileInfoList") != null) {
                componentMetaData.remove("fileInfoList");
            }
            if(componentMetaData.get("introduceInfoList") != null) {
                componentMetaData.remove("introduceInfoList");
            }
            if(componentMetaData.get("productInfoList") != null) {
                componentMetaData.remove("productInfoList");
            }
            if(componentMetaData.get("materialInfoList") != null) {
                componentMetaData.remove("materialInfoList");
            }
            addComponent.setComponentMetaData(componentMetaData.toJSONString());
        }
        if(componentDto.getComponentBusinessData() != null) {
            addComponent.setComponentBusinessData(componentDto.getComponentBusinessData());
        }
        addComponent.setSort(sort);
    }

    /**
     * 创建模板
     * @param dto
     * @return
     */
    private String createTemplate(EnterpriseCardTemplateComponentDto dto) {
        Date now = new Date();
        CardEnterpriseTemplateNew template = new CardEnterpriseTemplateNew();
        String templateId = IdUtil.simpleUUID();
        template.setBaseId(templateId);
        template.setEnterpriseId(dto.getEnterpriseId());
        if(StringUtils.isEmpty(dto.getTemplateName())){
            template.setTemplateName("未命名模板"+new Date().getTime());
        }

        template.setBaseCreateTime(now);
        template.setBaseCreateBy(dto.getUserId());
        template.setBaseUpdateBy(dto.getUserId());
        template.setBaseUpdateTime(now);
        template.setIsDelete(0);
        template.setVersion(dto.getVersion());
        template.setSourceTemplateId(dto.getSourceTemplateId());
        this.save(template);
        return templateId;
    }

    private void updateTemplate(EnterpriseCardTemplateComponentDto dto) {
        CardEnterpriseTemplateNew templateNew = new CardEnterpriseTemplateNew();
        templateNew.setBaseId(dto.getTemplateId());
        if(!StringUtils.isEmpty(dto.getTemplateName())){
            templateNew.setTemplateName(dto.getTemplateName());
        }
        templateNew.setBaseUpdateTime(new Date());
        templateNew.setBaseUpdateBy(dto.getUserId());
        this.baseMapper.updateById(templateNew);
    }

    private void checkParam(EnterpriseCardTemplateComponentDto dto) {
        if(StrUtil.isBlank(dto.getEnterpriseId())) {
            throw new BusinessException("企业标识不能为空");
        }
        // 判断快捷联系组件、企业实景组件是否大于1个
        List<TemplateComponentDto> componentDataList = dto.getComponentDataList();
        int baseLinkCount = 0;
        int enterpriseRealityCount = 0;
        if(CollectionUtil.isNotEmpty(componentDataList)) {
            for(TemplateComponentDto componentDto : componentDataList) {
                if(NewCardBusinessConstant.BASE_LINK.equals(componentDto.getComponentType())) {
                    baseLinkCount++;
                }else if(NewCardBusinessConstant.ENTERPRISE_REALITY.equals(componentDto.getComponentType())) {
                    enterpriseRealityCount++;
                }
            }
        }
        if(baseLinkCount > 1) {
            throw new BusinessException("最多只能添加一个【快捷联系】组件");
        }
        if(enterpriseRealityCount > 1) {
            throw new BusinessException("最多只能添加一个【企业实景】组件");
        }
    }

    private void checkNewLoginParam(EnterpriseCardTemplateComponentDto dto) {

        // 判断快捷联系组件、企业实景组件是否大于1个
        List<TemplateComponentDto> componentDataList = dto.getComponentDataList();
        int baseLinkCount = 0;
        int enterpriseRealityCount = 0;
        if(CollectionUtil.isNotEmpty(componentDataList)) {
            for(TemplateComponentDto componentDto : componentDataList) {
                if(NewCardBusinessConstant.BASE_LINK.equals(componentDto.getComponentType())) {
                    baseLinkCount++;
                }else if(NewCardBusinessConstant.ENTERPRISE_REALITY.equals(componentDto.getComponentType())) {
                    enterpriseRealityCount++;
                }
            }
        }
        if(baseLinkCount > 1) {
            throw new BusinessException("最多只能添加一个【快捷联系】组件");
        }
        if(enterpriseRealityCount > 1) {
            throw new BusinessException("最多只能添加一个【企业实景】组件");
        }
    }

    private void checkPreParam(EnterpriseCardTemplateComponentDto dto) {

        // 判断快捷联系组件、企业实景组件是否大于1个
        List<TemplateComponentDto> componentDataList = dto.getComponentDataList();
        int baseLinkCount = 0;
        int enterpriseRealityCount = 0;
        if(CollectionUtil.isNotEmpty(componentDataList)) {
            for(TemplateComponentDto componentDto : componentDataList) {
                if(NewCardBusinessConstant.BASE_LINK.equals(componentDto.getComponentType())) {
                    baseLinkCount++;
                }else if(NewCardBusinessConstant.ENTERPRISE_REALITY.equals(componentDto.getComponentType())) {
                    enterpriseRealityCount++;
                }
            }
        }
        if(baseLinkCount > 1) {
            throw new BusinessException("最多只能添加一个【快捷联系】组件");
        }
        if(enterpriseRealityCount > 1) {
            throw new BusinessException("最多只能添加一个【企业实景】组件");
        }
    }

    public List<PreSetTemplateListVo>  preSetTemplateList(TemplateListDto dto) {
        return this.getBaseMapper().preSetTemplateList(dto);
    }

    public List<PreSetTemplateListVo>  standardTemplateList(TemplateListDto dto) {
        return this.getBaseMapper().standardTemplateList(dto);
    }

    public PreSetTemplateListVo preSetTemplateDetailInfo(String templateId){
        return this.getBaseMapper().preSetTemplateDetailInfo(templateId);
    }

    public List<TemplateListVo>  templateList(TemplateListDto dto) {
        return this.getBaseMapper().templateList(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    public Message  deleteTemplate(String baseId) {
        Integer count = this.getBaseMapper().selectCount(new LambdaQueryWrapper<CardEnterpriseTemplateNew>().eq(CardEnterpriseTemplateNew::getSourceTemplateId, baseId));
        if(count > 0){
            return Message.fail("该模板已经被其他公司使用，不能删除");
        }
        this.getBaseMapper().deleteById(baseId);
        cardEnterpriseComponentService.remove(new LambdaQueryWrapper<CardEnterpriseComponent>().eq(CardEnterpriseComponent::getTemplateId, baseId));
        cardEnterpriseTemplateService.deleteByNewTemplateId(baseId);
        return Message.success();
    }

    /**
     * 保存或修改预置模板-运营后台使用
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdatePreTemplateInfo(EnterpriseCardTemplateComponentDto dto) {
        this.checkPreParam(dto);
        String templateId = "";
        // 1. 如果没有模板，则先创建模板
        if(StrUtil.isBlank(dto.getTemplateId())) {
            templateId = this.createTemplate(dto);
        }else {
            templateId = dto.getTemplateId();
            this.updateTemplate(dto);
        }
        // 2. 删除模板组件数据
        if(CollectionUtil.isNotEmpty(dto.getDeleteComponentIdList())) {
            cardEnterpriseComponentService.removeByIds(dto.getDeleteComponentIdList());
        }
        // 3. 保存模板组件数据
        if(CollectionUtil.isEmpty(dto.getComponentDataList())) {
            return;
        }
        List<CardEnterpriseComponent> updateComponentList = new ArrayList<>();
        List<CardEnterpriseComponent> addComponentList = new ArrayList<>();
        int sort = 1;
        for(TemplateComponentDto componentDto : dto.getComponentDataList()) {
            // 如果组件是文件类型，则解析文件id，并保存文件id。同时将文件提交审核
            if(NewCardBusinessConstant.FILE.equals(componentDto.getComponentType())) {
                this.setFileComponentData(templateId, componentDto);
            }
            // 如果组件id存在，则更新组件数据，否则新建数据
            if(StrUtil.isNotBlank(componentDto.getComponentId())) {
                CardEnterpriseComponent updateComponent = new CardEnterpriseComponent();
                updateComponent.setBaseId(componentDto.getComponentId());
                updateComponent.setComponentPageId(componentDto.getComponentPageId());
                updateComponent.setComponentPermission(componentDto.getComponentPermission());
                this.setComponentData(componentDto, updateComponent, sort);
                updateComponentList.add(updateComponent);
            }else {
                CardEnterpriseComponent addComponent = new CardEnterpriseComponent();
                addComponent.setBaseId(IdUtil.simpleUUID());
                addComponent.setTemplateId(templateId);
                addComponent.setComponentPermission(componentDto.getComponentPermission());
                addComponent.setComponentPageId(componentDto.getComponentPageId());
                this.setComponentData(componentDto, addComponent, sort);
                addComponentList.add(addComponent);
            }
            sort++;
        }
        if(CollectionUtil.isNotEmpty(updateComponentList)) {
            cardEnterpriseComponentService.updateBatchById(updateComponentList);
            // 根据组件权限更新使用该模板的名片的对应组件的数据。
            // 保存名片组件数据的表中template_component_id字段是模板组件表组件的主键，所以更新的数据是：template_component_id = 模板组件id，meta_data = 模板组件数据
            for(CardEnterpriseComponent component : updateComponentList) {
                if(component.getComponentPermission() == null || component.getComponentPermission().equals(NewCardBusinessConstant.TEMPLATE_COMPONENT_PERMISSION_1)) {
                    cardComponentDataMapper.updateCardComponentData(component.getBaseId(), component.getComponentMetaData(), component.getSort());
                }
            }
        }
        if(CollectionUtil.isNotEmpty(addComponentList)) {
            cardEnterpriseComponentService.saveBatch(addComponentList);
            // 查出所有使用该模板的名片，在每一张名片的组件数据中添加新组件
            List<String> useCurTemplateCardIdList = cardPersonalBaseInfoMapper.queryBaseIdListByTemplateId(templateId);
            if(CollectionUtil.isNotEmpty(useCurTemplateCardIdList)) {
                for(String cardId : useCurTemplateCardIdList) {
                    List<CardComponentData> newCardComponentDataList = new ArrayList<>();
                    for(CardEnterpriseComponent component : addComponentList) {
                        CardComponentData cardComponentData = this.buildCardComponentData(cardId, component);
                        newCardComponentDataList.add(cardComponentData);
                    }
                    cardComponentDataService.saveBatch(newCardComponentDataList);
                }
            }
        }
        CardEnterpriseTemplateDto subTemplate = dto.getSubTemplate();
        if(subTemplate != null){
            subTemplate.setNewTemplateId(templateId);
            subTemplate.setVersion(dto.getVersion());
            String baseId = subTemplate.getBaseId();
            if(StringUtils.isEmpty(baseId)){
                cardEnterpriseTemplateService.savePreTemplate(subTemplate);
            }else{
                cardEnterpriseTemplateService.updatePreTemplate(subTemplate);
            }


        }
        dto.setTemplateId(templateId);
        startProcess(dto);


    }

    private void startProcess(EnterpriseCardTemplateComponentDto dto){
        ShowRecordAuditDto queryDto = new ShowRecordAuditDto();
        queryDto.setBusinessRecordId(dto.getTemplateId());
        List<ShowRecordAuditVo> recordAuditInfos = showRecordAuditService.getRecordAuditInfo(queryDto);
        if(!CollectionUtils.isEmpty(recordAuditInfos)){
            long count = recordAuditInfos.stream().filter(f -> !ProcessStatus.REJECTED.equals(f.getStatus()) && !ProcessStatus.COMPLETED.equals(f.getStatus())).count();
            if(count > 0){
                return;
            }
        }
        Map<String, Object> variables = new HashMap();
        variables.put("applicant", dto.getUserId());
        ProcessInstance instance = workflowEngine.startProcess("two_step_approval", dto.getTemplateId(), variables, dto.getUserId(), "0");
        String currentNodeId = instance.getCurrentNodeId();
        List<TaskInstance> taskList = taskManager.findByTaskDefinitionIdAndInstanceId(currentNodeId, instance.getId());
        if(!CollectionUtil.isEmpty(taskList)){
            String taskId = taskList.get(0).getId();
            workflowEngine.completeTask(taskId, variables, null, dto.getUserId());

        }
    }

    public Message queryTemplateVersionByCardId(String cardId){
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
        if(cardBaseInfo == null){
            return Message.fail("名片不存在");
        }
        String cardVersion = cardBaseInfo.getCardVersion();
        String templateVersion = "unknown";
        /** 名片表中版本。1：个人版，2：试用版，3：付费正式版 4高级版  5拓客版  */
        //模板版本中版本 0为个人版  1为个人付费版 2为企业版
        if("1".equals(cardVersion)){
            templateVersion = "0";
        } else if (("2".equals(cardVersion) || "3".equals(cardVersion)) && StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
            templateVersion = "1";
        } else if (("2".equals(cardVersion) || "3".equals(cardVersion)  || "4".equals(cardVersion)   || "5".equals(cardVersion)) && !StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
            templateVersion = "2";
        }
        return Message.success(templateVersion);
    }


    @Transactional(rollbackFor = Exception.class)
    public Message editTemplateCardInfo(EnterpriseCardTemplateNewSaveDto dto) {
        String templateId = dto.getTemplateId();
        String subTemplateId = dto.getSubTemplateId();
        if(StringUtils.isEmpty(templateId) || StringUtils.isEmpty(subTemplateId)){
            return Message.fail("参数错误");
        }
        LambdaUpdateWrapper<CardEnterpriseTemplate> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(!StringUtils.isEmpty(dto.getBackgroundUrl()), CardEnterpriseTemplate::getBackgroundUrl, dto.getBackgroundUrl())
                .set(!StringUtils.isEmpty(dto.getBackgroundId()), CardEnterpriseTemplate::getBackgroundId, dto.getBackgroundId())
                .set(!StringUtils.isEmpty(dto.getTemplatePic()), CardEnterpriseTemplate::getTemplatePic, dto.getTemplatePic())
                .set(!StringUtils.isEmpty(dto.getLogo()), CardEnterpriseTemplate::getLogo, dto.getLogo())
                .set(dto.getLogoShowFlag() != null, CardEnterpriseTemplate::getLogoShowFlag, dto.getLogoShowFlag())
                        .eq(CardEnterpriseTemplate::getBaseId, subTemplateId);

        cardEnterpriseTemplateService.update(wrapper);

        List<CardTemplateStyleField> fieldList = dto.getFieldList();
        if(!CollectionUtils.isEmpty(fieldList)){
            styleFieldService.updateBatchById(fieldList);
        }


        //保存模板组件数据
        if(!CollectionUtil.isEmpty(dto.getComponentDataList())) {
            List<CardEnterpriseComponent> updateComponentList = new ArrayList<>();
            List<CardEnterpriseComponent> addComponentList = new ArrayList<>();
            int sort = 1;
            for(TemplateComponentDto componentDto : dto.getComponentDataList()) {
                // 如果组件是文件类型，则解析文件id，并保存文件id。同时将文件提交审核
                if(NewCardBusinessConstant.FILE.equals(componentDto.getComponentType())) {
                    this.setFileComponentData(templateId, componentDto);
                }
                // 如果组件id存在，则更新组件数据，否则新建数据
                if(StrUtil.isNotBlank(componentDto.getComponentId())) {
                    CardEnterpriseComponent updateComponent = new CardEnterpriseComponent();
                    updateComponent.setBaseId(componentDto.getComponentId());
                    updateComponent.setComponentPageId(componentDto.getComponentPageId());
                    updateComponent.setComponentPermission(componentDto.getComponentPermission());
                    this.setComponentData(componentDto, updateComponent, sort);
                    updateComponentList.add(updateComponent);
                }else {
                    CardEnterpriseComponent addComponent = new CardEnterpriseComponent();
                    addComponent.setBaseId(IdUtil.simpleUUID());
                    addComponent.setTemplateId(templateId);
                    addComponent.setComponentPermission(componentDto.getComponentPermission());
                    addComponent.setComponentPageId(componentDto.getComponentPageId());
                    this.setComponentData(componentDto, addComponent, sort);
                    addComponentList.add(addComponent);
                }
                sort++;
            }
            if(CollectionUtil.isNotEmpty(updateComponentList)) {
                cardEnterpriseComponentService.updateBatchById(updateComponentList);
                // 根据组件权限更新使用该模板的名片的对应组件的数据。
                // 保存名片组件数据的表中template_component_id字段是模板组件表组件的主键，所以更新的数据是：template_component_id = 模板组件id，meta_data = 模板组件数据
                for(CardEnterpriseComponent component : updateComponentList) {
                    if(component.getComponentPermission() == null || component.getComponentPermission().equals(NewCardBusinessConstant.TEMPLATE_COMPONENT_PERMISSION_1)) {
                        cardComponentDataMapper.updateCardComponentData(component.getBaseId(), component.getComponentMetaData(), component.getSort());
                    }
                }
            }

            if(CollectionUtil.isNotEmpty(addComponentList)) {
                cardEnterpriseComponentService.saveBatch(addComponentList);
                // 查出所有使用该模板的名片，在每一张名片的组件数据中添加新组件
                List<String> useCurTemplateCardIdList = cardPersonalBaseInfoMapper.queryBaseIdListByTemplateId(templateId);
                if(CollectionUtil.isNotEmpty(useCurTemplateCardIdList)) {
                    for(String cardId : useCurTemplateCardIdList) {
                        List<CardComponentData> newCardComponentDataList = new ArrayList<>();
                        for(CardEnterpriseComponent component : addComponentList) {
                            CardComponentData cardComponentData = this.buildCardComponentData(cardId, component);
                            newCardComponentDataList.add(cardComponentData);
                        }
                        cardComponentDataService.saveBatch(newCardComponentDataList);
                    }
                }
            }
        }


        return Message.success();

    }


    public CardEnterpriseTemplateDetailInfoVo templateDetailInfo(String templateId){
        return this.getBaseMapper().templateDetailInfo(templateId);
    }

    public CardEnterpriseMaterial getEnterpriseMaterialDetail(String materialId) {
        return cardEnterpriseMaterialService.getById(materialId);
    }

    @Transactional(rollbackFor = Exception.class)
    public Message  adminDeleteTemplate(String baseId) {
        Integer count = cardPersonalBaseInfoMapper.selectCount(new LambdaQueryWrapper<CardBaseInfo>().eq(CardBaseInfo::getTemplateId, baseId));
        if(count > 0){
            return Message.fail("该模板已经被员工使用，不能删除");
        }
        this.getBaseMapper().deleteById(baseId);
        cardEnterpriseComponentService.remove(new LambdaQueryWrapper<CardEnterpriseComponent>().eq(CardEnterpriseComponent::getTemplateId, baseId));
        cardEnterpriseTemplateService.deleteByNewTemplateId(baseId);
        return Message.success();
    }

    public TemplateComponentVo getMemberComponentsInfo(String cardId) {
        List<CardEnterpriseComponent> componentList = cardComponentDataMapper.selectMemberComponentsInfo(cardId);
        if(CollectionUtil.isEmpty(componentList)) {
            return null;
        }
        TemplateComponentVo templateComponentVo = new TemplateComponentVo();
        templateComponentVo.setTemplateId(componentList.get(0).getTemplateId());
        List<TemplateComponentDto> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent component : componentList) {
            TemplateComponentDto componentDto = new TemplateComponentDto();
            componentDto.setComponentId(component.getBaseId());
            componentDto.setComponentType(component.getComponentType());
            componentDto.setComponentBusinessData(component.getComponentBusinessData());
            componentDto.setSort(component.getSort());
            componentDto.setComponentPermission(component.getComponentPermission());
            componentDto.setComponentPageId(component.getComponentPageId());
            if(NewCardBusinessConstant.ENTERPRISE_PRODUCT.equals(component.getComponentType())) {
                // 产品组件的数据，将保存的产品id转换为具体的产品数据
                JSONObject productMetaData = this.setProductInfo(component);
                componentDto.setComponentMetaData(productMetaData);
            }else if(NewCardBusinessConstant.ENTERPRISE_SERVICE.equals(component.getComponentType())) {
                // 服务组件的数据，将保存的服务id转换为具体服务数据
                JSONObject serviceMetaData = this.setEnterpriseServiceInfo(component);
                componentDto.setComponentMetaData(serviceMetaData);
            } else if(NewCardBusinessConstant.FILE.equals(component.getComponentType())) {
                // 文件组件，从文件的审核结果表中查询数据
                componentDto.setComponentMetaData(this.setFileInfo(component));
            } else if(NewCardBusinessConstant.ENTERPRISE_MATERIAL.equals(component.getComponentType())) {
                // 物料组件，从物料表中查询数据，将物料id转换为物料的详情数据
                componentDto.setComponentMetaData(this.setEnterpriseMaterialInfo(component));
            } else if(NewCardBusinessConstant.COMPANY.equals(component.getComponentType()) || NewCardBusinessConstant.BUSINESS.equals(component.getComponentType())) {
                // 企业介绍和业务介绍属于图文组件，该组件中可能包含视频。查询视频的审核结果
                componentDto.setComponentMetaData(this.setImageTextInfo(component));
            }
            else {
                componentDto.setComponentMetaData(JSONObject.parseObject(component.getComponentMetaData()));
            }
            componentDataList.add(componentDto);
        }
        templateComponentVo.setComponentDataList(componentDataList);
        return templateComponentVo;
    }

    public void editMemberComponentsData(CardComponentData cardComponentData) {
        cardComponentDataService.update(new LambdaUpdateWrapper<CardComponentData>().eq(CardComponentData::getCardId, cardComponentData.getCardId())
                .eq(CardComponentData::getTemplateComponentId, cardComponentData.getTemplateComponentId())
                .set(CardComponentData::getComponentMetaData, cardComponentData.getComponentMetaData()));
    }

    @Transactional(rollbackFor = Throwable.class)
    public Message editMemberInfo(CardMemberInfoDto dto) {
        String cardId = dto.getCardId();
        CardBaseInfoDto cardBaseInfoDto = dto.getCardBaseInfo();
        List<CardStyleFieldData> memberStyleFields = dto.getMemberStyleFields();
        List<TemplateComponentDto> components = dto.getComponents();
        if (cardBaseInfoDto != null) {
            CardBaseInfo cardBaseInfo = new CardBaseInfo();
            cardBaseInfo.setBaseId(cardId);
            cardBaseInfo.setPubScreenshotUrl(cardBaseInfoDto.getPubScreenshotUrl());
            cardPersonalBaseInfoMapper.updateById(cardBaseInfo);
        }
        if (memberStyleFields == null || memberStyleFields.isEmpty()) {
            return Message.fail("保存数据无效");
        }
        // 同步更新 card_base_info 表
        CardBaseInfo cardBaseInfo = new CardBaseInfo();
        cardBaseInfo.setBaseId(cardId);
        int flag = 0;
        for (CardStyleFieldData memberStyleField : memberStyleFields) {
            CardTemplateStyleField cardTemplateStyleField = cardTemplateStyleFieldMapper.selectById(memberStyleField.getStyleFieldId());
            if ("姓名".equals(cardTemplateStyleField.getBaseName())) {
                cardBaseInfo.setName(memberStyleField.getStyleFieldValue());
                flag = 1;
            }
            if ("职位".equals(cardTemplateStyleField.getBaseName())) {
                cardBaseInfo.setPositionOne(memberStyleField.getStyleFieldValue());
                flag = 1;
            }
            if ("手机".equals(cardTemplateStyleField.getBaseName())) {
                cardBaseInfo.setEnterpriseMobile(memberStyleField.getStyleFieldValue());
                flag = 1;
            }
            if ("邮箱".equals(cardTemplateStyleField.getBaseName())) {
                cardBaseInfo.setEnterpriseEmail(memberStyleField.getStyleFieldValue());
                flag = 1;
            }
        }
        if (flag == 1) {
            cardPersonalBaseInfoMapper.updateById(cardBaseInfo);
        }
        cardStyleFieldDataService.remove(new LambdaQueryWrapper<CardStyleFieldData>().eq(CardStyleFieldData::getCardId, cardId));
        List<CardStyleFieldData> dataList = memberStyleFields.stream().peek(i -> {
            i.setBaseId(IdUtil.simpleUUID());
            i.setCardId(cardId);
        }).collect(Collectors.toList());
        cardStyleFieldDataService.saveBatch(dataList);
        if (components != null && !components.isEmpty()) {
            for (TemplateComponentDto component : components) {
                cardComponentDataService.update(new LambdaUpdateWrapper<CardComponentData>().eq(CardComponentData::getCardId, component.getCardId())
                        .eq(CardComponentData::getTemplateComponentId, component.getTemplateComponentId())
                        .set(CardComponentData::getComponentMetaData, new Gson().toJson(component.getComponentMetaData())));
            }
        }
        return Message.success("保存成功");
    }

    public Message getMemberTemplateInfo(String styleId, String templateId, String cardId, String templateType) {
        Message message = cardEnterpriseTemplateService.templateStyleDetail(styleId, templateId, cardId, templateType);
        if (!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
            return message;
        }
        CardEnterpriseTemplateDto cardEnterpriseTemplateDto = (CardEnterpriseTemplateDto) message.getObj();
        List<CardStyleFieldData> memberStyleFields = cardStyleFieldDataService.list(new LambdaQueryWrapper<CardStyleFieldData>().eq(CardStyleFieldData::getCardId, cardId));
        cardEnterpriseTemplateDto.setMemberStyleFields(memberStyleFields);
        return Message.success(cardEnterpriseTemplateDto);
    }

    @Transactional(rollbackFor = Exception.class)
    public Message chooseAndSaveTemplateInfo(EnterpriseCardTemplateComponentDto dto) {
        this.checkNewLoginParam(dto);
        EnterpriseCardAddParamDto param =dto.getEnterpriseCardAddParam();
        if(param == null){
            return Message.fail("传参有误，企业信息没传");
        }
        if(dto.getSubTemplate() != null){
            List<CardTemplateStyleField> templateStyleFieldList = dto.getSubTemplate().getFieldList();
            if (!CollectionUtil.isEmpty(templateStyleFieldList)){
                for (CardTemplateStyleField field : templateStyleFieldList){
                    field.setBaseId(IdUtil.simpleUUID());
                    if("commonName".equals(field.getFieldName())){
                        String enterpriseName = param.getEnterpriseName();
                        Map<String, Object> extraInfo = field.getExtraInfo();
                        extraInfo.put("text", enterpriseName);
                    }
                }
            }
            param.setTemplateStyleFieldList(templateStyleFieldList != null ? templateStyleFieldList : new ArrayList<CardTemplateStyleField>());
        }

        String templateId = "";
        // 1. 如果没有模板，则先创建模板
        if(StrUtil.isBlank(dto.getTemplateId())) {
            templateId = this.createTemplate(dto);

            //保存企业以及名片用户

            param.setTemplateId(templateId);
            Message message = enterpriseNewCardService.addNewEnterpriseCard(param);
            if(message.getCode() != MessageCodeConstant.MSG_SUCCESS_CODE){
                return message;
            }
            String enterpriseId = param.getEnterpriseId();
            dto.setEnterpriseId(enterpriseId);
            this.update(new LambdaUpdateWrapper<CardEnterpriseTemplateNew>().set(CardEnterpriseTemplateNew::getEnterpriseId, enterpriseId).eq(CardEnterpriseTemplateNew::getBaseId, templateId));


            //创建模板的分享配置
            //CardShareConfig cardShareConfig = cardShareConfigService.buildCardShareConfig(dto.getEnterpriseId(), templateId);
            //cardShareConfigService.save(cardShareConfig);
        }else {
            templateId = dto.getTemplateId();
            this.updateTemplate(dto);
        }
        // 2. 删除模板组件数据
        if(CollectionUtil.isNotEmpty(dto.getDeleteComponentIdList())) {
            cardEnterpriseComponentService.removeByIds(dto.getDeleteComponentIdList());
            // 删除使用这些组件的名片上的数据
            cardComponentDataMapper.deleteByTemplateComponentIdList(dto.getDeleteComponentIdList());
        }
        // 3. 保存模板组件数据
        List<CardEnterpriseComponent> updateComponentList = new ArrayList<>();
        List<CardEnterpriseComponent> addComponentList = new ArrayList<>();
        int sort = 1;
        for(TemplateComponentDto componentDto : dto.getComponentDataList()) {
            // 如果组件是文件类型，则解析文件id，并保存文件id。同时将文件提交审核
            if(NewCardBusinessConstant.FILE.equals(componentDto.getComponentType())) {
                this.setFileComponentData(templateId, componentDto);
            }
            // 企业介绍和业务介绍组件都属于图片文本类型，里面可能包含视频。将提交的视频相关的数据进行处理并提交审核
            if(NewCardBusinessConstant.COMPANY.equals(componentDto.getComponentType()) || NewCardBusinessConstant.BUSINESS.equals(componentDto.getComponentType())) {
                this.setImageTextComponentData(templateId, componentDto);
            }
            // 如果组件id存在，则更新组件数据，否则新建数据
            if(StrUtil.isNotBlank(componentDto.getComponentId())) {
                CardEnterpriseComponent updateComponent = new CardEnterpriseComponent();
                updateComponent.setBaseId(componentDto.getComponentId());
                updateComponent.setComponentPageId(componentDto.getComponentPageId());
                updateComponent.setComponentPermission(componentDto.getComponentPermission());
                this.setComponentData(componentDto, updateComponent, sort);
                updateComponentList.add(updateComponent);
            }else {
                CardEnterpriseComponent addComponent = new CardEnterpriseComponent();
                addComponent.setBaseId(IdUtil.simpleUUID());
                addComponent.setTemplateId(templateId);
                addComponent.setComponentPermission(componentDto.getComponentPermission());
                addComponent.setComponentPageId(componentDto.getComponentPageId());
                this.setComponentData(componentDto, addComponent, sort);
                addComponentList.add(addComponent);
            }
            sort++;
        }
        if(CollectionUtil.isNotEmpty(updateComponentList)) {
            cardEnterpriseComponentService.updateBatchById(updateComponentList);
            // 根据组件权限更新使用该模板的名片的对应组件的数据。
            // 保存名片组件数据的表中template_component_id字段是模板组件表组件的主键，所以更新的数据是：template_component_id = 模板组件id，meta_data = 模板组件数据
            for(CardEnterpriseComponent component : updateComponentList) {
                if(component.getComponentPermission() == null || component.getComponentPermission().equals(NewCardBusinessConstant.TEMPLATE_COMPONENT_PERMISSION_1)) {
                    cardComponentDataMapper.updateCardComponentData(component.getBaseId(), component.getComponentMetaData(), component.getSort());
                }
            }
        }
        if(CollectionUtil.isNotEmpty(addComponentList)) {
            cardEnterpriseComponentService.saveBatch(addComponentList);
            // 查出所有使用该模板的名片，在每一张名片的组件数据中添加新组件
//            List<String> useCurTemplateCardIdList = cardAuditMapper.queryCardIdList(templateId, null);
//            if(CollectionUtil.isNotEmpty(useCurTemplateCardIdList)) {
//                for(String cardId : useCurTemplateCardIdList) {
//                    List<CardComponentData> newCardComponentDataList = new ArrayList<>();
//                    for(CardEnterpriseComponent component : addComponentList) {
//                        CardComponentData cardComponentData = this.buildCardComponentData(cardId, component);
//                        newCardComponentDataList.add(cardComponentData);
//                    }
//                    cardComponentDataService.saveBatch(newCardComponentDataList);
//                }
//            }
            //生成名片的组件数据
            enterpriseNewCardService.createCardComponentData(addComponentList, param.getCardId());
        }
        CardEnterpriseTemplateDto subTemplate = dto.getSubTemplate();
        if(subTemplate != null){
            subTemplate.setNewTemplateId(templateId);
            subTemplate.setEnterpriseId(dto.getEnterpriseId());
            String baseId = subTemplate.getBaseId();
            subTemplate.setEnterpriseAdminCardId(param.getCardId());
            if(StringUtils.isEmpty(baseId)){
                cardEnterpriseTemplateService.saveTemplate(subTemplate);
            }else{
                cardEnterpriseTemplateService.updateTemplate(subTemplate);
            }


        }
        return Message.success();

    }
}
